<?php

namespace App\Http\Controllers\API\Books;

use DB;
use Config;
use App\Http\Controllers\API\ApiController;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
use App\Eloqumd\Book\BookArticleLatest;
use App\Eloqumd\Book\BookArticlePublish;
use App\Eloqumd\Book\BookArticleVersion;
use App\Validate\Book\BookValidator;

class ArticleController extends ApiController
{
    // 根据ID获取最新文章
    public function getArticleById(Request $request)
    {
        $id = $request->input('id', 0);
        $v = $request->input('v', 0);
        // 0 = 正在编辑，1 = 发布获取
        $type = $request->input('type', 0);
        if ($v) {
            $artVersion = BookArticleVersion::find($id);
            return $this->jsonReturns(10000, $this->success, [
                'artVersion' => $artVersion
            ], 'get', trans('alg.Get-Art-Version-Info', ['version' => $artVersion['versions']]));
        }

        if ($type == 1) {
            $artPublish = BookArticlePublish::find($id);
            return $this->jsonReturns(10000, $this->success,  $artPublish, 'get', trans('alg.Get-Art-Publish-Info', ['name' => $artPublish['title']]));
        }

        $artLatest = BookArticleLatest::find($id);
        $artPublish = BookArticlePublish::where('sysunique', $artLatest['sysunique'])->first();

        return $this->jsonReturns(10000, $this->success, [
            'artLatest' => $artLatest,
            'artPublish' => $artPublish,
        ], 'get', trans('alg.Get-Art-Latest-Info', ['name' => $artLatest['title']]));
    }

    // 文章创建
    public function articleCreated(Request $request)
    {
        $type = $request->input('type', 0);
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = BookValidator::articleCreated($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'create/verror', trans('alg.Create-Art-And-Validate-Error'));
        }

        // 开启事物
        DB::beginTransaction();
        try {
            $sysunique = Uuid::uuid1()->getHex();
            $createdAt = date('Y-m-d H:i:s');

            $model = new BookArticleLatest;
            $model->cate_id = $param['cate_id'];
            $model->title = $param['title'];
            $model->content = $param['content'];
            $model->content_html = $param['art-editormd-html-code'];
            $model->orders = $param['orders'] ?? 10;
            $model->created_at = $createdAt;
            $model->sysunique = $sysunique;
            $model->author = $param['author'] ?? $this->apiUser['user_real_name'];
            if ($type == 1) {
                $model->ispublish = 1;
            }
            $model->save();

            $artID = $model->id;

            $model = new BookArticlePublish;
            $model->cate_id = $param['cate_id'];
            $model->title = $param['title'];
            $model->content = $param['content'];
            $model->content_html = $param['art-editormd-html-code'];
            $model->orders = $param['orders'] ?? 10;
            $model->created_at = $createdAt;
            $model->sysunique = $sysunique;
            $model->author = $param['author'] ?? $this->apiUser['user_real_name'];
            if ($type == 1) {
                $model->ispublish = 1;
            }
            $model->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                ['id' => $artID],
                'create',
                trans('alg.Create-Art-Success', [
                    'name' => $param['title'],
                    'type' => ($type == 1 ? trans('alg.Publish') : trans('alg.Save')),
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'create/error', trans('alg.Create-Art-System-Error'));
        }
    }

    // 文章修改
    public function articleModified(Request $request)
    {
        $type = $request->input('type', 0);
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = BookValidator::articleModified($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'modify/verror', trans('alg.Modify-Art-And-Validate-Error'));
        }

        // 开启事物
        DB::beginTransaction();
        try {
            $updatedAt = date('Y-m-d H:i:s');

            $model = BookArticleLatest::find($param['id']);
            $sysunique = $model->sysunique;

            $model->cate_id = $param['cate_id'];
            $model->title = $param['title'];
            $model->content = $param['content'];
            $model->content_html = $param['art-editormd-html-code'];
            $model->orders = $param['orders'] ?? 10;
            $model->updated_at = $updatedAt;
            $model->author = $param['author'] ?? $this->apiUser['user_real_name'];
            if ($type == 1) {
                $model->ispublish = 1;
            } else {
                $model->ispublish = 0;
            }
            $model->save();

            $pulishArt = BookArticlePublish::where('sysunique', $sysunique)->first()->toArray();
            $publishID = $pulishArt['id'];
            // 如果编辑为保存，且展示表为未发布，或者编辑为发布，且展示表为未发布  同步更新即可
            if ((!$type && !$pulishArt['ispublish']) || ($type && !$pulishArt['ispublish'])) {
                $model = BookArticlePublish::find($publishID);
                $model->cate_id = $param['cate_id'];
                $model->title = $param['title'];
                $model->content = $param['content'];
                $model->content_html = $param['art-editormd-html-code'];
                $model->orders = $param['orders'] ?? 10;
                $model->updated_at = $updatedAt;
                $model->author = $param['author'] ?? $this->apiUser['user_real_name'];
                if ($type == 1) {
                    $model->ispublish = 1;
                }
                $model->save();
            // 如果编辑为发布，且展示表未已发布，同步更新的同时，需要将上一个版本置为历史版本
            } elseif ($type && $pulishArt['ispublish']) {
                // 历史版本记录
                $pulishArt['versions'] = 'v-' . date('Ymd') . '-' . date('His');
                unset($pulishArt['id']);
                $artV = new BookArticleVersion;
                $artV->insert($pulishArt);

                $model = BookArticlePublish::find($publishID);
                $model->cate_id = $param['cate_id'];
                $model->title = $param['title'];
                $model->content = $param['content'];
                $model->content_html = $param['art-editormd-html-code'];
                $model->orders = $param['orders'] ?? 10;
                $model->updated_at = $updatedAt;
                $model->author = $param['author'] ?? $this->apiUser['user_real_name'];
                $model->ispublish = 1;
                $model->save();
            }

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                ['id' => $param['id']],
                'modify',
                trans('alg.Modify-Art-Success', [
                    'name' => $param['title'],
                    'type' => ($type == 1 ? trans('alg.Publish') : trans('alg.Save')),
                ])
            );


        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'modify/error', trans('alg.Modify-Art-System-Error'));
        }
    }

    // 删除文章
    public function articleDeleted(Request $request)
    {
        $sysunique = $request->input('sysunique', '');

        // 开启事物
        DB::beginTransaction();
        try {
            BookArticleLatest::where('sysunique', $sysunique)->update(['isdel' => 1]);
            BookArticleVersion::where('sysunique', $sysunique)->update(['isdel' => 1]);

            DB::commit();

            return $this->jsonReturns(10000, $this->success, [], 'delete', trans('alg.Delete-Art-Success'));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'delete/error', trans('alg.Delete-Art-System-Error'));
        }
    }

    // 获取文章信息版本
    public function getArticleVeriosn(Request $request)
    {
        $sysunique = $request->input('sysunique', '');

        $artVersionData = BookArticleVersion::where('sysunique', $sysunique)
            ->select(['id', 'title', 'versions'])
            ->where('isdel', 0)
            ->get();

        return $this->jsonReturns(10000, $this->success, $artVersionData, 'get', trans('alg.Get-Art-Version-List'));
    }

    // 文章分享
    public function getArticleShares(Request $request)
    {
        $artId = $request->input('art_id', 0);
        // 0=最新编辑，1=已发布
        $type = $request->input('type', 0);

        // 文章信息
        $artData = !$type ? BookArticleLatest::find($artId) : BookArticlePublish::find($artId);
        // 生成唯一key
        $key = uniqid();
        $enArtId = simple_encrypt($artId, 'E', $key);
        $enArtType = simple_encrypt($type, 'E', $key);

        // $sharePath = get_domain(request()->server()) . '/api/ae5e0de8771711eab205f0761cb312e?art_id=' . $enArtId . '&_timestamp=' . $key . '&_signastype=' . $enArtType;
        $sharePath = 'http://localhost:8088' . '/api/ae5e0de8771711eab205f0761cb312e?art_id=' . $enArtId . '&_timestamp=' . $key . '&_signastype=' . $enArtType;

        return $this->jsonReturns(10000, $this->success, [
            'title' => $artData['title'],
            'author' => $artData['author'],
            'sharePath' => $sharePath
        ], 'share', trans('alg.Get-Art-Share-Path', ['name' => $artData['title'], 'type' => ($type == 1 ? trans('alg.Publish') : trans('alg.Editing'))]));
    }
}
